import {ref, computed} from 'vue'
import {getMailCodeAPI} from "@/api/login.js";

const env = import.meta.env
const CODE_AGAIN_TIME = Number.parseInt(env.VITE_CODE_AGAIN_TIME) || 60

// ********************
// * 获取验证码按钮的状态 *
// ********************
export const codeBtnDisable = ref(false)
export const codeBtnLoading = ref(false)

// ***********************
// * 再次获取验证码所需的时间 *
// ***********************
export const codeAgainTime = ref(CODE_AGAIN_TIME + 1)

// ********************
// * 获取验证码按钮的文本 *
// ********************
export const codeBtnText = computed(() => {
    if (codeBtnLoading.value) return '获取验证码中...'
    if (codeAgainTime.value === CODE_AGAIN_TIME + 1) return '获取验证码'
    else return `再次获取：${codeAgainTime.value}s`
})

// 保存计时器，用于计时器的清除
let interval = null

// ************
// * 获取验证码 *
// ************
export function getCode(mail) {
    codeBtnDisable.value = true
    codeBtnLoading.value = true
    // 调用获取验证码 API 发送请求
    getMailCodeAPI(mail).then(
        res => {
            codeBtnLoading.value = false
            // 发生验证码失败
            if (!res) {
                codeBtnDisable.value = false
                return
            }
            codeAgainTime.value -= 1
            clearInterval(interval)
            interval = setInterval(() => {
                codeAgainTime.value -= 1
                if (codeAgainTime.value <= 0) {
                    codeAgainTime.value = CODE_AGAIN_TIME + 1
                    codeBtnDisable.value = false
                    clearInterval(interval)
                }
            }, 1000)
        }
    ).catch(
        // 发生验证码发生错误
        () => {
            codeBtnLoading.value = false
            codeBtnDisable.value = false
        }
    )
}